package com.zaimokuza.cn.service.impl;

import com.zaimokuza.cn.entity.constants.FileConstant;
import com.zaimokuza.cn.entity.enums.CustomizeExceptionEnum;
import com.zaimokuza.cn.service.FileService;
import com.zaimokuza.cn.util.AssertUtils;
import com.zaimokuza.cn.util.RandomUtils;
import com.zaimokuza.cn.util.TimeUtils;
import com.zaimokuza.cn.util.grace.GraceException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static com.zaimokuza.cn.entity.constants.FileConstant.AVATAR_EXPAND_FOLDER;

/**
 * @author zaimokuza
 */
@Service
public class FileServiceImpl implements FileService {

    /**
     * 存储文件
     *
     * @param file      文件对象
     * @param basicPath 基础路径
     * @return 文件路径
     * @throws IOException IOException
     */
    public String uploadFile(MultipartFile file, String basicPath) throws IOException {
        // 校验图片
        AssertUtils.notNull(file, CustomizeExceptionEnum.FILE_ERROR);
        // 图片名称
        String fileName = file.getOriginalFilename();
        AssertUtils.notBlank(fileName, CustomizeExceptionEnum.FILE_ERROR);
        // 文件类型
        int subBeginIndex = fileName.lastIndexOf(".");
        int subEndIndex = fileName.length();
        String fileType = fileName.substring(subBeginIndex, subEndIndex);
        AssertUtils.notBlank(fileType, CustomizeExceptionEnum.FILE_TYPE_ERROR);
        // 根据日期生成实际存储文件夹路径
        String[] split = TimeUtils.getDate().split("-");
        String additionalFolderPath = split[0] + "/" + split[1] + "/";
        // 校验文件夹是否存在,如果不存在创建文件夹
        File folder = new File(basicPath + additionalFolderPath);
        if (!folder.exists()) {
            boolean mkdirResult = folder.mkdirs();
            if (!mkdirResult) {
                GraceException.display(CustomizeExceptionEnum.FILE_MKDIR_ERROR, "创建文件夹失败:" + basicPath + additionalFolderPath);
            }
        }
        // 生成实际文件存储路径并存储文件
        String filePath = additionalFolderPath + RandomUtils.get32Uid() + fileType;
        file.transferTo(new File(basicPath + filePath));
        // 返回文件路径
        return filePath;
    }

    @Override
    public String uploadAvatar(MultipartFile file) throws IOException {
        // 上传文件并生成虚拟文件路径
        return FileConstant.IMAGE_VIRTUAL_FOLDER + AVATAR_EXPAND_FOLDER + uploadFile(file, FileConstant.IMAGE_ACTUAL_FOLDER + AVATAR_EXPAND_FOLDER);
    }

    @Override
    public String uploadImage(MultipartFile file) throws IOException {
        // 上传文件并生成虚拟文件路径
        return FileConstant.IMAGE_VIRTUAL_FOLDER + uploadFile(file, FileConstant.IMAGE_ACTUAL_FOLDER);
    }

}
